<?php
// ------------------------------------------------------------------------------------
// Bestand:       Query
// Versie:        1.0
// Projekt:       Cursus MasterClass van Eduvision
// Datum:         14-07-2008
// Auteur(s):     Ronald Obbens
// Email(s):      ronaldobbens@gmail.com
// Revisie(s):	  
//
// Beschrijving:  Query builder to pair the models with the database framework
// ------------------------------------------------------------------------------------
//

require_once('DataBase.php');

class Query
{
	private $m_sQuery;
	private $m_aParams;
	private $m_aColums;
	private $m_sPrefix;
	private $m_sSortMethod;
	private $m_iLimit;
	private $m_sTable;
	private $m_iPrimairyKey;

	/**
	 * Set the most important variables
	 *
	 */
	public function __construct()
	{
		$this->m_sTable = null;
		$this->m_iPrimairyKey = null;
	}
	
	
	/**
	 * Set the DB table which hase to be used
	 *
	 * @param string $p_sTableName
	 */
	public function setTable($p_sTableName)
	{
		$this->m_sTable = $p_sTableName;	
	}
	
	/**
	 * If needed, set the primairy key of the record needed
	 *
	 * @param integer $p_iPrimairyKey
	 */
	public function setPrimairyKey($p_iPrimairyKey)
	{
		$this->m_iPrimairyKey = $p_iPrimairyKey;
	}
	
	/**
	 * return last defined by number
	 *
	 * @param int $p_iNumber
	 */
	public function getLimit($p_iNumber)
	{
		return Database::getInstance()->runQuery( "SELECT Id FROM " . $this->m_sTable . " LIMIT '" . $p_iNumber . "'");
	}
	
	/**
	 * Execute a SELECT cq GET query from the database
	 * if query return one field return mysql_object else return mysql_array
	 *
	 * @param string $p_sKey
	 * @return DBoutput
	 */
	public function get($p_sKey)
	{ 
		return Database::getInstance()->runQuery( "SELECT " . $p_sKey . " FROM " . $this->m_sTable . " WHERE id = '" . $this->m_iPrimairyKey . "'")->getData();
		
	}
	

	/**
	 * Set the correspondending field in the database. 
	 * if the primairy key isn't set make it an insert query and return it's id
	 *
	 * @param string $p_sKey
	 * @param string_type $p_sValue
	 * @return DBoutput
	 */
	public function set($p_sKey,$p_sValue)
	{
		if(isset($this->m_iPrimairyKey))
		{
			$DB = DataBase::getInstance();
			$output = $DB->runQuery("UPDATE " . $this->m_sTable . " SET " . $p_sKey . "='" . $p_sValue . "' WHERE Id='" . $this->m_iPrimairyKey . "'");
			return $output;
		}
		else
		{
			$DB = DataBase::getInstance();
			$output = $DB->runQuery("INSERT INTO " . $this->m_sTable . " (" . $p_sKey . ") VALUES ('" . $p_sValue . "')");
			return $output;
		}
	}
	
}
?>